package cn.chair.util;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import life.innovation.exception.BaseException;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.util.TextUtils;
import org.springframework.beans.factory.annotation.Value;

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

public class SmallUtil {




    //  key
    private  static int key = 163;

    /**
     * 将分为单位的转换为元 （除100）
     *
     * @param amount
     * @return
     * @throws Exception
     */
    /**金额为分的格式 */
    private static final String CURRENCY_FEN_REGEX = "\\-?[0-9]+";
    public static String changeF2Y(String amount) throws Exception{
        if(!amount.matches(CURRENCY_FEN_REGEX)) {
            throw new Exception("金额格式有误");
        }
        return BigDecimal.valueOf(Long.valueOf(amount)).divide(new BigDecimal(100)).toString();
    }
    /**
     * 增加时间
     * @param second 分钟
     * */
    public static String addMinute(int second)
    {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.SECOND, second);
        return  sdf.format(nowTime.getTime());
    }

    public static String getTransTime()
    {
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(d);
    }

    // 低位在前
    public  static String changLow(String str)
    {
        int javaReadInt =  Integer.parseInt(str,16);
        byte byte4 = (byte) (javaReadInt & 0xff);
        byte byte3 = (byte) ((javaReadInt & 0xff00) >> 8);
        byte byte2 = (byte) ((javaReadInt & 0xff0000) >> 16);
        byte byte1 = (byte) ((javaReadInt & 0xff000000) >> 24);
        int realint = (byte1& 0xff)<<0  |(byte2& 0xff)<<8 | (byte3& 0xff)<< 16| (byte4& 0xff)<<24 ;
        return Integer.toHexString(realint).toUpperCase();
    }

    public static byte[] doSign(byte[] src)
    {
        byte [] dst = new byte[8];
        for(int i=0;i<dst.length;i++)
        {
            dst[i] = (byte)(src[i]^key);
        }
        return dst;
    }
    public static byte[] byteMerger(byte[] bt1, byte[] bt2){
        byte[] bt3 = new byte[bt1.length+bt2.length];
        System.arraycopy(bt1, 0, bt3, 0, bt1.length);
        System.arraycopy(bt2, 0, bt3, bt1.length, bt2.length);
        return bt3;
    }
    /**
     * base64字符串转换成图片
     * @param imgStr        base64字符串
     * @param imgFilePath   图片存放路径
     * @return
     */
    public static boolean Base64ToImage(String imgStr,String imgFilePath) { // 对字节数组字符串进行Base64解码并生成图片

        if (SmallUtil.isEmpty(imgStr)) // 图像数据为空
            return false;

        Base64 decoder = new Base64();
        try {
            // Base64解码
            byte[] b = decoder.decode(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }

            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();

            return true;
        } catch (Exception e) {
            return false;
        }

    }


    /**
     * 判断手机格式是否正确
     * @param mobiles
     * @return
     */
    public static boolean isMobileNO(String mobiles) {
        String telRegex = "[1][12345789]\\d{9}" ;
        if (TextUtils.isEmpty(mobiles)) return false ;
        else return mobiles.matches( telRegex ) ;
    }
    /**
     * 6位随机验证码
     * @charCount 位数
     * @return
     */
    public static String getRandNum(){
        Random rad=new Random();
        String result  = rad.nextInt(1000000) +"";
        if(result.length()!=6){
            return getRandNum();
        }
        return result;
    }

    @Value("${jwt.private.key}")
    private static String jwtKey;

    public static Claims getClaimsFromToken(String token)
    {
        Claims claims;
        try {
            claims = Jwts.parser()
                    .setSigningKey(jwtKey)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            claims = null;
        }
        return claims;
    }
    public static byte[] subBytes(byte[] src, int begin, int count) {
        byte[] bs = new byte[count];
        System.arraycopy(src, begin, bs, 0, count);
        return bs;
    }


    public static String getAuth(String appid,String appkey) throws BaseException, UnsupportedEncodingException
    {
        byte[] authBytes = java.util.Base64.getEncoder().encode((appid + ":" + appkey).getBytes());
        String authStr = new String(authBytes, "UTF-8");
        return "Basic " + authStr;
    }
    public static boolean isEmpty(String str) {
        return (str == null) || str.trim().equalsIgnoreCase("null")
                || (str.trim().length() < 1) || str.equals("")|| str.equals("0.00")|| str.equals("0.0")|| str.equals("0")|| str.equals("0.");
    }
    public static String formatDouble(double dou){
        DecimalFormat decimalFormat   = new DecimalFormat("######0.00");
        return decimalFormat.format(dou);
    }
    public static double addDouble(double   v1,double   v2)
    {
        BigDecimal b1 = new   BigDecimal(Double.toString(v1));
        BigDecimal b2 =   new   BigDecimal(Double.toString(v2));
        return b1.add(b2).doubleValue();
    }

    public static Double sub(Double v1,Double v2){
        BigDecimal b1 = new BigDecimal(v1.toString());
        BigDecimal b2 = new BigDecimal(v2.toString());
        return b1.subtract(b2).doubleValue();
    }
    private String parseCardId(String cardId) {
        if (!cardId.contains("-")) {
            return cardId;
        }

        String[] hexArray = cardId.split("-");
        String hexStr = "";

        for (int i = hexArray.length - 1; i >= 0; i--) {
            String hex = hexArray[i];
            hexStr += hex;
        }

        return String.format("%010d", Long.parseLong(hexStr, 16));
    }

    /**
     *  逢一进一，并保留两位小数
     * */
    public static String formatNumberPay(String number){
        number = new BigDecimal(number).setScale(2, BigDecimal.ROUND_UP)+"";
        return number;
    }

}
